package org.jeecg.modules.hc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.micrometer.core.instrument.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.hc.entity.HcCompanyFoodList;
import org.jeecg.modules.hc.entity.HcCompanyFoodSpecifications;
import org.jeecg.modules.hc.service.IHcCompanyFoodListService;
import org.jeecg.modules.hc.service.IHcCompanyFoodSpecificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 企业订餐菜品设置
 * @Author: jeecg-boot
 * @Date:   2023-07-10
 * @Version: V1.0
 */
@Api(tags="企业订餐菜品设置")
@RestController
@RequestMapping("/hc/hcCompanyFoodList")
@Slf4j
public class HcCompanyFoodListController extends JeecgController<HcCompanyFoodList, IHcCompanyFoodListService> {
	@Autowired
	private IHcCompanyFoodListService hcCompanyFoodListService;
	@Autowired
	private IHcCompanyFoodSpecificationsService hcCompanyFoodSpecificationsService;

	/**
	 * 企业订餐菜品查询
	 */
	@ApiOperation(value="企业订餐菜品查询", notes="企业订餐菜品查询")
	@GetMapping(value = "/listNewByCompanyId")
	public Result<?> getListNewByCompanyId(@RequestParam(name="companyId") String companyId) {
		return Result.OK(hcCompanyFoodSpecificationsService.getListNewByCompanyId(companyId));
	}

	/**
	 * 企业订餐菜品设置
	 */
	@ApiOperation(value="企业订餐菜品设置", notes="企业订餐菜品设置")
	@GetMapping(value = "/listNew")
	public Result<?> queryPageListNew(@RequestParam(name="companyId") String companyId,
									  @RequestParam(name="merchantId") String merchantId,
									  String keyWord) {
		LambdaQueryWrapper<HcCompanyFoodList> foodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
		foodListLambdaQueryWrapper.eq(HcCompanyFoodList::getCompanyId,companyId).eq(HcCompanyFoodList::getMerchantId,merchantId);
		if (StringUtils.isNotBlank(keyWord)){
			foodListLambdaQueryWrapper.like(HcCompanyFoodList::getFoodName,keyWord);
		}
		List<HcCompanyFoodList> list = hcCompanyFoodListService.list(foodListLambdaQueryWrapper);
		list.forEach( r -> {
			String isUseSpecifications = r.getIsUseSpecifications();
			if (isUseSpecifications.equalsIgnoreCase("yes")){
				LambdaQueryWrapper<HcCompanyFoodSpecifications> specificationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
				specificationsLambdaQueryWrapper.eq(HcCompanyFoodSpecifications::getFoodsId,r.getId());
				List<HcCompanyFoodSpecifications> all =hcCompanyFoodSpecificationsService.list(specificationsLambdaQueryWrapper);
				List<HcCompanyFoodSpecifications> specificationsList = all.stream().filter(s -> StringUtils.isEmpty(s.getParentId())).collect(Collectors.toList());
				List<HcCompanyFoodSpecifications> foodSpecifications = getNextFoodSpecifications(specificationsList, all);
				r.setSpecifications(foodSpecifications);
			}
		});
		return Result.OK(list);
	}


	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyFoodList
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="企业订餐菜品查询", notes="企业订餐菜品查询")
	@GetMapping(value = "/list")
	public Result<IPage<HcCompanyFoodList>> queryPageList(HcCompanyFoodList hcCompanyFoodList,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HcCompanyFoodList> queryWrapper = QueryGenerator.initQueryWrapper(hcCompanyFoodList, req.getParameterMap());
		Page<HcCompanyFoodList> page = new Page<HcCompanyFoodList>(pageNo, pageSize);
		IPage<HcCompanyFoodList> pageList = hcCompanyFoodListService.page(page, queryWrapper);
		List<HcCompanyFoodList> records = pageList.getRecords();
		List<HcCompanyFoodList> newRecords = new ArrayList<>();
		records.forEach( r -> {
			String isUseSpecifications = r.getIsUseSpecifications();
			if (isUseSpecifications.equalsIgnoreCase("yes")){
				LambdaQueryWrapper<HcCompanyFoodSpecifications> specificationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
				specificationsLambdaQueryWrapper.eq(HcCompanyFoodSpecifications::getFoodsId,r.getId());
				List<HcCompanyFoodSpecifications> all =hcCompanyFoodSpecificationsService.list(specificationsLambdaQueryWrapper);
				List<HcCompanyFoodSpecifications> specificationsList = all.stream().filter(s -> StringUtils.isEmpty(s.getParentId())).collect(Collectors.toList());
				List<HcCompanyFoodSpecifications> foodSpecifications = getNextFoodSpecifications(specificationsList, all);
				r.setSpecifications(foodSpecifications);
			}
			newRecords.add(r);
		});
		pageList.setRecords(newRecords);
		return Result.OK(pageList);
	}

	private List<HcCompanyFoodSpecifications> getNextFoodSpecifications(List<HcCompanyFoodSpecifications> specifications,List<HcCompanyFoodSpecifications> all){
		//遍历上级规格找到对应的下级规格
		specifications.forEach(s -> {
			List<HcCompanyFoodSpecifications> specifications1 = new ArrayList<>();
			all.forEach( a -> {
				if (StringUtils.isNotBlank(a.getParentId())){
					if (a.getParentId().equals(s.getId())){
						specifications1.add(a);
						String isUseSpecifications = a.getIsUseSpecifications();
						if (isUseSpecifications.equalsIgnoreCase("yes")){
							List<HcCompanyFoodSpecifications> specificationList = a.getNextSpecifications();
							getNextFoodSpecifications(specificationList,all);
						}
					}
				}
			});
			s.setNextSpecifications(specifications1);
		});
		return specifications;
	}



	/**
	 *   添加
	 *
	 * @param hcCompanyFoodList
	 * @return
	 */
	@AutoLog(value = "企业订餐菜品设置-添加")
	@ApiOperation(value="企业订餐菜品设置-添加", notes="企业订餐菜品设置-添加")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_list:add")
	@PostMapping(value = "/add")
	public Result<String> addNew(@RequestBody HcCompanyFoodList hcCompanyFoodList) {
		hcCompanyFoodList.setBuyedNum(hcCompanyFoodList.getLimitNum());
		hcCompanyFoodListService.saveNew(hcCompanyFoodList);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hcCompanyFoodList
	 * @return
	 */
	@AutoLog(value = "企业订餐菜品设置-编辑")
	@ApiOperation(value="企业订餐菜品设置-编辑", notes="企业订餐菜品设置-编辑")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_list:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HcCompanyFoodList hcCompanyFoodList) {
		hcCompanyFoodListService.updateNew(hcCompanyFoodList);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业订餐菜品设置-通过id删除")
	@ApiOperation(value="企业订餐菜品设置-通过id删除", notes="企业订餐菜品设置-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_list:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hcCompanyFoodListService.removeNew(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业订餐菜品设置-批量删除")
	@ApiOperation(value="企业订餐菜品设置-批量删除", notes="企业订餐菜品设置-批量删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_food_list:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList= (List<String>) Arrays.asList(ids.split(","));
		idList.forEach(i -> {
			hcCompanyFoodListService.removeNew(i);
		});
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "企业订餐菜品设置-通过id查询")
	@ApiOperation(value="企业订餐菜品设置-通过id查询", notes="企业订餐菜品设置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HcCompanyFoodList> queryById(@RequestParam(name="id",required=true) String id) {
		HcCompanyFoodList hcCompanyFoodList = hcCompanyFoodListService.getById(id);
		if(hcCompanyFoodList==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hcCompanyFoodList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hcCompanyFoodList
    */
    //@RequiresPermissions("org.jeecg.modules:hc_company_food_list:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcCompanyFoodList hcCompanyFoodList) {
        return super.exportXls(request, hcCompanyFoodList, HcCompanyFoodList.class, "企业订餐菜品设置");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("hc_company_food_list:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcCompanyFoodList.class);
    }

}
